package com.fingard.dsp.bank.directbank.bos01;

import com.fingard.dsp.bank.directbank.bankInterface.IAuthorizeForRec;
import com.fingard.dsp.bank.reqrespobj.authforrec.*;
import com.fingard.dsp.bank.reqrespobj.authforrec.detail.RetAtsQryAuthForRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.Date;

public class BOS01AuthorizeForRec extends BOS01Base implements IAuthorizeForRec {
	@Override
	public RetAtsAuthForRec d_auth(ReqAuthForRec p_req) throws Exception {
		RetAtsAuthForRec retAts = new RetAtsAuthForRec(p_req.reqHeader);
		retAts.reqSeqID = p_req.reqSeqID;
		
        try {
        	StringBuilder seqNoMappingContent = new StringBuilder();
        	
        	StringBuilder sbFileContent = new StringBuilder();
        	String batRecProtocolNo = getBankConfig().getValueAsString("batRecProtocolNo");
        	if (StringHelper.isNullOrEmpty(batRecProtocolNo)) {
        		WriteBankLogLn("缺失'批量代扣编号-batRecProtocolNo'配置节点!");
        		retAts.respCode = "-1";
            	retAts.respInfo = "缺失'批量代扣编号-batRecProtocolNo'配置节点!";
            	return retAts;
        	}
        	
        	String tmpReqHeader = MessageFormat.format("{0}|{1}|{2}", p_req.totalNum, batRecProtocolNo, "0");
			sbFileContent.append(tmpReqHeader).append("\r\n");
			
			int index = 0;
        	while (p_req.readRecord()) {
        		index++;
                String tmpReqBodyDetail = MessageFormat.format("{0}|{1}|{2}", index, p_req.readedDetail.oppActName, p_req.readedDetail.oppAct);
				sbFileContent.append(tmpReqBodyDetail).append("\r\n");
				
				seqNoMappingContent.append(p_req.readedDetail.authCode).append(",").append(index).append("\r\n");
            }
        	WriteBankLogLn2("待上传批次白名单文件内容:\r\n" + sbFileContent.toString());
            
        	String tmpUploadFileName = "WF_" + bankFront.org + "_" + p_req.reqSeqID + ".txt";
			String tmpLocalMarkPath = getTempFileDirectory() + File.separator + "ENDIIMPT" + File.separator + tmpUploadFileName;
			WriteBankLogLn2("批次白名单文件保存本机路径: " + tmpLocalMarkPath);
			FileHelper.writeFile(tmpLocalMarkPath, sbFileContent.toString(), getCharset());
            
			WriteBankLogLn2("本地批次白名单流水映射文件内容:\r\n" + seqNoMappingContent.toString());
			String tmpBatSeqNoPath = getDataFileDirectory(new Date()) + File.separator + p_req.reqSeqID + ".txt";
			WriteBankLogLn2("本地批次白名单流水映射文件路径:" + tmpBatSeqNoPath);
			FileHelper.writeFile(tmpBatSeqNoPath, seqNoMappingContent.toString(), getCharset());
        	
			String[] tmpStrRet = uploadFile(tmpLocalMarkPath, p_req.reqSeqID, "ENDIIMPT");
			if (tmpStrRet[0].length() == 0) {
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
				if (tmpBkReader != null) {
					retAts.respCode = "0";
					
                    String tmpRespCode = tmpBkReader.getFirstText("/BOSEBankData/opRep/retCode");
                    if ("0".equals(tmpRespCode)) {
                    	retAts.retCode = "2";
                    } else {
                    	retAts.retCode = "1";
                    }
                    retAts.serialNo = p_req.reqSeqID;
                    retAts.retMsg = tmpBkReader.getFirstText("/BOSEBankData/opRep/errMsg");
                } else {
                	retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
        } catch (Exception ex) {
        	ex.printStackTrace();
        	retAts.respCode = "-1";
        	retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        
        retAts.writeRetToATS();
        return retAts;
	}

	@Override
	public RetAtsQryAuthForRec d_qry_auth(ReqQryAuthForRec p_req) throws Exception {
		RetAtsQryAuthForRec retAts = new RetAtsQryAuthForRec(p_req.reqHeader);
		retAts.reqSeqID = p_req.reqSeqID;
        retAts.writeStart();
        
        try {
        	String tmpBatSeqNoPath = getDataFileDirectory(new Date()) + File.separator + p_req.reqSeqID + ".txt";
			WriteBankLogLn2("本地批次白名单流水映射文件路径:" + tmpBatSeqNoPath);
			if (!new File(tmpBatSeqNoPath).exists()) {
				retAts.respCode = "-1";
				retAts.respInfo = "本地批次映射文件不存在!";
				return retAts;
			}
			String seqNoMappingContent = FileHelper.readFileText(tmpBatSeqNoPath, getCharset());
			WriteBankLogLn2("本地批次白名单流水映射文件内容:\r\n" + seqNoMappingContent.toString());
			String[] seqNoArray = seqNoMappingContent.split("\r\n");
			
        	String[] tmpStrRet = downloadFile(p_req.reqSeqID, p_req.reqSeqID, "", "ENDIIMPT");
        	if (tmpStrRet[0].length() == 0) {
        		if (tmpStrRet[1].contains("<")) {
        			tmpStrRet[1] = tmpStrRet[1].substring(tmpStrRet[1].indexOf("<"));
        			StringBuilder tmpSbMsg = new StringBuilder();
					XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
					if(tmpBkReader != null) {
						retAts.respCode = "-1";
	            		retAts.respInfo = tmpBkReader.getFirstText("/BOSEBankData/opRep/errMsg");
					} else {
						retAts.respCode = "-1";
	            		retAts.respInfo = tmpSbMsg.toString();
					}
					retAts.writeAfterDetail();
					return retAts;
        		}
        		String tmpRetStr = FileHelper.readFileText(tmpStrRet[1], getCharset());
            	WriteBankLogLn2("本地批次白名单结果文件内容:\r\n" + tmpRetStr);
            	
            	if (StringHelper.hasAnyChar(tmpRetStr)) {
            		retAts.respCode = "0";
					
					StringReader strReader = new StringReader(tmpRetStr);
					BufferedReader tmpReader = new BufferedReader(strReader);
					tmpReader.readLine();
					
					while(true) {
						String eachline = tmpReader.readLine();
						if(eachline == null){
							break;
						}
						if (eachline.indexOf("|") > 0) {
							// 明细记录:序号0|户名1|卡号2|返回结果3|失败原因4
							String[] bodyValues = eachline.split("\\|");
							for (String tmpSeqNo : seqNoArray) {
								if (StringHelper.isNullOrEmpty(tmpSeqNo)) {
									continue;
								}
								if ((tmpSeqNo.split(",")[1]).equals(bodyValues[0])) {
									RetAtsQryAuthForRecDetail tmpDetail = new RetAtsQryAuthForRecDetail();
				                    tmpDetail.iSeqno = tmpSeqNo.split(",")[0];
				                    
				                    tmpDetail.contractNo = tmpDetail.iSeqno;
				                    tmpDetail.authCode = tmpDetail.iSeqno;
				                    tmpDetail.oppAct = bodyValues[2];
				                    tmpDetail.oppActName = bodyValues[1];
				                    String tmpResult = bodyValues[3];
				                    if ("成功".equals(tmpResult)) {
				                        tmpDetail.transState = "2";
				                        tmpDetail.payInfo = tmpResult;
				                    } else {
				                        tmpDetail.transState = "3";
				                        tmpDetail.payInfo = bodyValues[4];
				                    }
				                    tmpDetail.payCode = tmpResult;
				                    retAts.writeRetDetail(tmpDetail);
								}
							}
						} else {
							retAts.respCode = "-1";
		            		retAts.respInfo = "银行返回明细数据格式非法!";
						}
					}
            	} else {
            		retAts.respCode = "-1";
            		retAts.respInfo = "本地批次结果文件内容为空!";
            	}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
        } catch (Exception ex) {
        	ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        
        retAts.writeAfterDetail();
        return retAts;
	}

	@Override
	public RetAtsQryRecAuthInfo d_qry_authInfo(ReqQryRecAuthInfo p_req) throws Exception {
		return null;
	}
}
